package cn.yun.web.response;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建一个对象.在内存中代表一张图片(验证码图片对象)
        int width = 100;
        int height = 50;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //2.美化图片
          //2.1填充背景色
        Graphics graphics = image.getGraphics();//获取画笔对象
        graphics.setColor(Color.PINK);//设置画笔颜色为粉红色
        graphics.fillRect(0,0,width,height); //填充整个图片对象
         //2.2画图片的边框
        graphics.setColor(Color.blue);
        graphics.drawRect(0,0,width-1,height-1);
        //2.3写验证码
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        //生成随机脚标
        Random r=new Random();

        for (int j = 1; j <=4; j++) {
            int index = r.nextInt(str.length());
            char ch = str.charAt(index);
            graphics.drawString(ch+"",width/5*j,height/2);
        }

       /* graphics.drawString("a",20,25);
        graphics.drawString("b",40,25);
        graphics.drawString("c",60,25);
        graphics.drawString("d",80,25);*/

        //2.4画干扰线
        graphics.setColor(Color.green);

        //随机产生6条线
        for (int i = 0; i <6 ; i++) {
            //随机生成坐标点
            int x1 = r.nextInt(width);
            int x2 = r.nextInt(width);
            int y1 = r.nextInt(height);
            int y2 = r.nextInt(height);

            graphics.drawLine(x1,y1,x2,y2);//两个坐标点确定一条线
        }
      //  graphics.drawLine(1,1,5,5);//两个坐标点确定一条线


        //3.将图片输出到页面展示
        ImageIO.write(image, "jpg", response.getOutputStream());

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request,response);
    }

}
